﻿
//新创建试题为false,修改试题为true
var isEdit = false;
////var singleQuestionGUID = $("#hSingleQuestionGUID").Value();
//if (singleQuestionGUID) {
//}
var isRender = false;
var normalShowTime = 0;
//缓动时间
var time50 = 50;
var time100 = 100;
var time200 = 200;
var time500 = 500;

//试题信息对象
var questionInfo = {
    examPaperGUID: "",
    sectionGUID: "",
    tigan: "",
    knowledgePoint: [],
    typeValue: 1,            //1为单选，2为多选，3为填空，4为判断，5为简答
    typeValueChineseName: "",
    score: 0,                //单个试题分数
    sn: 0,                   //排序
    options: [],             //选项集合
    optionObj: {             //选项对象
        Key: "",
        Value: ""
    },
    standarAnswer: "",       //选项正确答案
    itemsTotal: 4,           //单选或者多选的选项数目
    order: 1,                  //题目序号
    QuestionPureText: "",
    AnswerAnalysis: ""          //试题解析
};


var editArea = $("#editArea");
if (!$(".question-review .group-question").length) {
    editArea.slideDown(time500);
}


//定义弹框的文本框、保存和取消按钮
var input, save, cancel;

var score = $("#question-value-number input");

//单选 多选 填空 简答
var questionType = $(".tixing ul li a");
var options = $(".option");


//选择单选 多选等..

var index = 0;//题型默认选择为单选0；
if ($("#hSingleQuestionType").val()) {
    index = parseInt($("#hSingleQuestionType").val()) - 1;
}

//获取编辑试题的guid和设置知识点
if ($("#hSingleQuestionGUID").val()) {
    isEdit = true;
    questionInfo.examPaperGUID = $("#hSingleQuestionGUID").val();
    var knowledgePointStrNew = "";
    //设置知识点
    $('#singleFieldTags span.tagit-label').each(function () {
        knowledgePointStrNew = knowledgePointStrNew + $(this).html() + ',';
    });
    $("#zhishidian").val(knowledgePointStrNew.substring(0, knowledgePointStrNew.length - 1));
     var t3Ul = $("#tab3 ul");
     var t3LiWithItemC = t3Ul.children("li.editorItem");
     t3LiWithItemC.each(function () {
         var inputval = $(this).children("input");
         if (!inputval) {
             $(this).children("input").val("a");
         }
         AddTagitEvent($(this), false);
     })
}
else {
    resetEditArea();
}
questionType.click(function () {
    index = questionType.index(this);

    //题目类型切换
    questionType.removeClass("selected");
    questionType.eq(index).addClass("selected");
    options.hide();
    options.eq(index).show();


})

//添加知识点绑定事件
if ($(".tagit-close").length > 0) {
    $(".tagit-close").click(function () {
        $(this).parent().remove();
        var knowledgePointStrNew = "";
        $('#singleFieldTags span.tagit-label').each(function () {
            knowledgePointStrNew = knowledgePointStrNew + $(this).html() + ',';
        });
        $("#zhishidian").val(knowledgePointStrNew.substring(0, knowledgePointStrNew.length - 1));
    })
}


//编辑区域-选择题选项添加与删除
optionAddAndDelete();


//初始化编辑器节点
var myEditor = $("#editor");
var editorInitialized = false; // 判断编辑器是否初始化，用于提交试题时判断，是否给题干赋值
ume.ready(function () {
    myEditor = $("#editor");
    toggleUMEditor(); //编辑器与文本框切换
    ume.focus();
    ume.setContent(""); // 初始化不置空的话，编辑器里面会有空格
    $('.edui-container').hide();
    //ume.addListener("blur", function (type, event) {
    //    myEditor.hide();
    //    $("#tiganInfo,.option ul li.item .optionInput").show();
    //});
});


//提交试题
$(".submit-button .confirm").click(function () {

    /*为空验证*********************************************************************************************************************/
    //一级、二级、三级不能为空
    if ($("#selFirst").val() == "") {
        layer.tips('一级分类不能为空', ("#selFirst"), { tips: [2, '#f06150'] });
        return;
    }

    //将编辑器中的值赋给文本框
    if ($.trim(getUMEditorContent()) && myEditor.parents('.edui-container').siblings(".optionInput").length) {
        myEditor.parents('.edui-container').siblings(".optionInput").html($.trim(getUMEditorContent()));
    } 

    //验证编辑栏输入是否为空
    if (!$.trim($("#tiganInfo").html())) {
        layer.tips('题干不能为空', $(".tigan-text"), { tips: [2, '#f06150'] });
        return;
    }

    //验证选择题内容与答案是否为空
    if (index == 0 || index == 1) {
        var standarAnswerDom = options.eq(index).children(".right-xuanxiang").children(".xuanxiang-group").children("a");
        var standarAnswerCount = 0;//答案数目
        var testInput = options.eq(index).children("ul").children(".item"); //选项集合
        for (var t = 0; t < testInput.length; t++) {

            //选择题答案内容不能为空
            if (!$.trim(testInput.eq(t).children(".editorDiv").children(".optionInput").html())) {
                layer.tips('选项值不能为空', testInput.eq(t).children(".editorDiv"), { tips: [2, '#f06150'] });
                return;
            }

            //获取标准答案数目
            if (standarAnswerDom.eq(t).hasClass("selected")) {
                standarAnswerCount++;
            }
        }

        //选择题答案不能为空
        if (!standarAnswerCount) {
            layer.tips('请选择试题答案！', standarAnswerDom.last(), { tips: [2, '#f06150'] });
            return;
        }
    }
    /*为空验证*********************************************************************************************************************/

    //当为填空题 --内容不能为空
    if (index == 2) {
        var sumAnswer = "";
        var isUnCheckAnsSeqInput = $("#UnCheckAnsSeqInput").is(":checked");
        var tAnswer = options.eq(index).find("input.tiankong_inputContent");
        if (tAnswer.length > 0) {
            for (var j = 0; j < tAnswer.length; j++) {
                var thisAnswerInput = tAnswer.eq(j);
                var thisAnswer = $.trim(tAnswer.eq(j).val());
                if (!thisAnswer) {
                    var textDiv = thisAnswerInput.siblings('div.text')
                    if (textDiv) {
                        var inputNow = textDiv.find("input");
                        if (inputNow && inputNow.val()) {
                            layer.tips('输入回车完成答案录入！', tAnswer.eq(j).siblings(".text"), { tips: [2, '#f06150'] });
                            return;
                        }
                    }
                    layer.tips('请填写试题答案！', tAnswer.eq(j).siblings(".text"), { tips: [2, '#f06150'] });
                    return;
                }
            }
        }
        else {
            layer.msg('填空题最少需要一个答案！');
            return;
        }
    }
    if (!CheckTiankongHaveRepeat()) {
        layer.msg("不检验顺序时，答案不能重复！")
        return false;
    }


    getQuestionInfo(index);//获取用户输入的试题数据信息

    questionInfo.tigan = $("#tiganInfo").html();

    questionInfo.knowledgePoint = $.trim($("#zhishidian").val()).split(",");
    
    questionInfo.QuestionPureText = $("#tiganInfo").text();


    //questionInfo.sectionGUID = $(this).parent().parent().siblings(".question-title").attr("data-sectionguid");

    //if (!questionInfo.sectionGUID) {
    //    questionInfo.sectionGUID = $("#hCurrentSectionGuid").val();
    //}

    //将单题添加到选择的栏目下
    var columns = $("#input-group").children(".input-block");
    var selectedColumns = new Array();
    for (var i = 0; i < columns.length; i++) {
        if (columns.eq(i).children("input").attr("checked")) {
            selectedColumns.push(columns.eq(i).attr("data-sectionguid"));
        }
    }

    //试题解析
    questionInfo.AnswerAnalysis = $("#explanation .optionInput").html();

    var obj = {
        TradeFirstGenreCode: $("#selFirst").val(),
        TradeSecondGenreCode: $("#selSecond").val(),
        TradeThirdGenreCode: $("#selThird").val(),
        QuestionTitle: questionInfo.tigan,
        QuestionPureText: questionInfo.QuestionPureText,
        questionGUID: questionInfo.examPaperGUID,
        KnowledgePoint: questionInfo.knowledgePoint,
        Type: questionInfo.typeValue,
        Option: questionInfo.options,
        StandardAnswer: questionInfo.standarAnswer,
        FavoriteGuids: selectedColumns,
        AnswerAnalysis: questionInfo.AnswerAnalysis

        //ExamPaperGUID: questionInfo.examPaperGUID,
        //SectionGUID: questionInfo.sectionGUID,
        //SN: questionInfo.order,
        //Score: questionInfo.score,
        
    };

    //新建试题
    try {
        var loadingLayer = loadingAnimation();
        if (!isEdit) {
            $.ajax({
                type: "POST",
                url: DomainUrlHelper.InstituCenterAction + "api/ApiSingleQuestion/CreateSingleQuestion",
                contentType: "application/json", //必须有
                dataType: "json", //表示返回值类型，不必须
                data: JSON.stringify(obj),  //相当于 //data: "{'str1':'foovalue', 'str2':'barvalue'}",
                success: function (jsonResult) {
                    consoleLog(jsonResult);
                    if (jsonResult.ErrorCode == "E0006") {

                        index = 0;//恢复默认状态
                        layer.msg("新建成功，可继续添加单题！");
                        
                        resetEditArea();
                    }
                    else {
                        layer.msg(jsonResult.ErrorMessage);

                    }
                    layer.close(loadingLayer);
                }
            });
        }
            //编辑试题
        else {
            //删除点击编辑试题时隐藏的试题
            //if ($(this).parent().parent().prev().css("display") == "none") {
            //    $(this).parent().parent().prev().remove();
            //}

            $.ajax({
                type: "POST",
                url: DomainUrlHelper.InstituCenterAction + "api/ApiSingleQuestion/EditSingleQuestion",
                contentType: "application/json", //必须有
                dataType: "json", //表示返回值类型，不必须
                data: JSON.stringify(obj),  //相当于 //data: "{'str1':'foovalue', 'str2':'barvalue'}",
                success: function (jsonResult) {
                    consoleLog(jsonResult);
                    if (jsonResult.ErrorCode == "E0006") {

                        //isEdit = false;//编辑试题的标识

                        //index = 0;//恢复默认状态
                        layer.msg("试题修改成功！")
                        //resetEditArea();

                        //window.close();
                    }
                    else {
                        layer.msg(jsonResult.ErrorMessage);
                        //isEdit = false;//编辑试题的标识
                    }
                    layer.close(loadingLayer);
                }
            });
        }

    } catch (e) {
        layer.close(loadingLayer);
        layer.msg("提交失败！错误代码：" + e);
    }


})

//取消编辑试题
$(".submit-button .cancel").click(function () {
    index = 0;//恢复默认状态

    $("#editor").hide();
    $("#tiganInfo").html("").show();
    $("#zhishidian").val("");
    //$(".option").find(".optionInput").html("");
    //var option = $(".option");
    $(".editorDiv .optionInput").html("").show();
    $("#jianda").val("");
    $('#singleFieldTags').children().not('li.tagit-new').remove();

    //题型部分重新恢复至初始状态

    //重置选择题选项
    var t1 = $("#tab1 ul");
    var t2 = $("#tab2 ul");
    resetOptionItems(t1);
    resetOptionItems(t2);

    //重置填空题选项
    var t3 = $("#tab3 ul");
    if (t3.children(".editorItem").length > 1) {
        for (var k = t3.children(".editorItem").length; k > 1; k--) {
            t3.children(".editorItem").eq(k - 1).remove();
        }
    }

    //重置判断题选项
    var t4 = $("#tab4 .xuanxiang-group a");
    t4.removeClass("selected").eq(0).addClass("selected");

    //设置试题类型
    var tx = $("#tixing");
    tx.children("ul").children("li").children("a").removeClass("selected").eq(0).addClass("selected");
    tx.siblings(".option").hide().eq(0).show();


    isEdit = false;//编辑试题的标识

    window.location.href = "http://saishi.cnki.net";
})


//试题编辑栏的显隐
toggleEditAreaBar();


//选择题与判断题答案选择
selectAnswer();

//添加新分组 栏目
var groupBox = $("#add-group-box");
$("#add-group").click(function () {
    groupBox.show();
})
//取消添加新分组 栏目
$("#add-group-box .add-new-group-cancel").click(function () {
    groupBox.hide();
})
//确定添加新分组 栏目
$("#add-group-box .add-new-group-submit").click(function () {
    var columnName = $.trim(groupBox.children("input").val());
    if (columnName.length > 0) {
        if (checkInput(columnName)) {
            var group = $("#input-group");
            var groupChildren = group.children(".input-block");
            var groupChildrenLength = groupChildren.length;
            var flag = -1;//标示是否含有相同名称的栏目
            for (var i = 0; i < groupChildrenLength; i++) {
                if ($.trim(groupChildren.eq(i).children("label").html()) == columnName) {
                    flag = i;
                    layer.msg("已存在相同名字的分组！");
                    $("#new-group-input-area").select();
                    break;
                }
            }
            if (flag == -1) {
                $.post(DomainUrlHelper.InstituCenterAction + "Institutioninfo/AddFavoriteName", {
                    txtName: columnName
                }, function (data) {
                    consoleLog(data);
                    if (data.ErrorCode = "E0006") {

                        var columnStr = '<div class="input-block" data-sectionGuid=' + data.favoriteGUID + '>' +
                                        '<input type="checkbox" id="group' + groupChildrenLength + '">' +
                                        ' <label for="group' + groupChildrenLength + '">' + columnName + '</label>' +
                                     '</div>';
                        group.append(columnStr);
                    }
                    else {
                        layer.msg("非法字符！")
                    }
                })
            }
        }
        else {
            layer.msg("新分组名不能包含特殊字符！")
        }
    }
    else {
        layer.tips('分组名不能为空', $("#new-group-input-area"), { tips: [2, '#f06150'] });
    }
})

if (!isEdit) {
    //获取栏目
    getColumnsForSave();
}

//获取栏目
function getColumnsForSave() {
   
    var columnStr = '';

    $.getJSON(DomainUrlHelper.InstituCenterAction+"api/ApiInstitutioninfo/SearchFavaror", {}, function (data) {
        consoleLog(data);
        if (data.ErrorCode == "E0006") {
            for (var i = 0; i < data.FavoritQeuestions.length; i++) {
                columnStr += '<div class="input-block" data-sectionGuid="' + data.FavoritQeuestions[i].FavoriteGUID + '">' +
                                '<input type="checkbox" id="group' + i + '">' +
                                ' <label for="group' + i + '">' + data.FavoritQeuestions[i].Question + '</label>' +
                             '</div>';
            }
            $("#input-group").append(columnStr);
        }
        else {
            layer.msg("栏目加载失败！")
        }
    })
}

// 点击空白区域编辑器隐藏
document.onmousedown = hideEditor;
function hideEditor(e) {
    //如果编辑器隐藏，则返回
    if (myEditor.parents(".edui-container").is(':hidden'))
        return true;
    e = e || event;
    var typename = "";
    var oid = "";
    var className = "";

    if (e.srcElement) {
        typename = e.srcElement.tagName;
        oid = e.srcElement.getAttribute("id");
        className = e.srcElement.getAttribute("class");
    } else if (e.target) {
        typename = e.target.tagName;
        oid = e.target.getAttribute("id");
        className = e.target.getAttribute("class");
    }

    if (className) {
        ConsoleLog("Time:" + (new Date()).toLocaleString() + ",ClassName=" + className);
    }
    else {
        ConsoleLog("Time:" + (new Date()).toLocaleString() + ",ClassName= null");
    }
    //if ((typename == "HTML" || typename == "DIV" || typename == "BODY") && oid != "editor" && className.indexOf("optionInput") < 0) {
    //如果编辑器隐藏，则不需要执行隐藏操作
    if (!myEditor.parents(".edui-container").is(':hidden'))
    {
        if (oid != "editor" && className && className.indexOf("optionInput") < 0 && className.indexOf("edui-icon") < 0 && className.indexOf("edui-") < 0) {

            //隐藏编辑器
            if ($('#kfEditorContainerDiv').css("z-index") == -1) {//当公式编辑器窗口隐藏时，才允许执行隐藏编辑器操作
                ConsoleLog("Time:" + (new Date()).toLocaleString() + ",ClassName=" + className + ",隐藏编辑器");
                myEditor.parents('.edui-container').siblings(".optionInput").html(getUMEditorContent());
                myEditor.parents(".edui-container").siblings(".optionInput").show();
                myEditor.parents(".edui-container").hide();
            }
        }
    }

    return true;
}

//解析试题显示与隐藏
$("#addExplanation").click(function () {
    $("#explanation-tab").hide();
    $("#explanation").show();
})
$("#explanation .false").click(function () {
    $("#explanation-tab").show();
    $("#explanation").hide();
    $("#explanation").find(".optionInput").html("");
})